//
//  rgb-convertor.c
//  FFMPEG-Serial-Demo
//
//  Created by aron on 2017/12/27.
//  Copyright © 2017年 aron. All rights reserved.
//

#include "rgb-convertor.h"
#include <stdio.h>
#include <stdlib.h>

/**
 * Split R, G, B planes in RGB24 file.
 * @param url  Location of Input RGB file.
 * @param w    Width of Input RGB file.
 * @param h    Height of Input RGB file.
 * @param num  Number of frames to process.
 *
 */
int simplest_rgb_split(char *url, int w, int h, int num) {
    FILE* rgbFile = fopen(url, "rb+");
    FILE* rOutFile = fopen("rgb_out_r.y", "wb+");
    FILE* gOutFile = fopen("rgb_out_g.y", "wb+");
    FILE* bOutFile = fopen("rgb_out_b.y", "wb+");
    
    unsigned char *picData=(unsigned char *)malloc(w*h*3);
    
    // 读取原始图像数据
    fread(picData, 1, w*h, rgbFile);
    
    for (int i = 0; i<num; i++) {
        for (int j = 0; j<w*h; j+=3) {
            // 读取R通道写入到文件
            fwrite(picData + j, 1, 1, rOutFile);
            // 读取G通道写入到文件
            fwrite(picData + j + 1, 1, 1, gOutFile);
            // 读取B通道写入到文件
            fwrite(picData + j + 2, 1, 1,bOutFile);
        }
    }
    
    free(picData);
    fclose(rgbFile);
    fclose(rOutFile);
    fclose(gOutFile);
    fclose(bOutFile);
    
    return 0;
}
